package cn.rjzjh.tapestry.tams.pages.sys.common;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.tapestry5.PersistenceConstants;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.hibernate.annotations.CommitAfter;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.json.JSONArray;
import org.apache.tapestry5.json.JSONObject;
import org.apache.tapestry5.util.TextStreamResponse;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.ProjectionList;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;

import cn.rjzjh.commons.util.web.OperateResult;
import cn.rjzjh.tapestry.busi.model.ca.CaPosition;
import cn.rjzjh.tapestry.busi.model.ca.CaStaff;
import cn.rjzjh.tapestry.busi.model.ca.CaStaffPosition;
import cn.rjzjh.tapestry.busi.service.IOrgService;
import cn.rjzjh.tapestry.component.tools.TapestryAssist;
import cn.rjzjh.tapestry.tams.base.ParentPage;
import cn.rjzjh.tapestry.tams.services.base.IHbService;

public class PositionAssign extends ParentPage {
	@Inject
	private IOrgService orgService;
	@Inject
	private Session session;
	@Property
	private String orgTree;
	@Inject
	private IHbService hbService;
	@Persist(PersistenceConstants.CLIENT)
	@Property
	private int staffId;
	@Persist(PersistenceConstants.CLIENT)
	private JSONArray orgs;

	@Property
	private List<CaStaffPosition> allPosition;// 已选中组织中拥有的群组

	@Property
	private List<String> selPosition;// 已分派到的群组

	public TextStreamResponse onInitByOrg() {
		JSONObject params=TapestryAssist.packParams(request);
		orgs = TapestryAssist.getParams(params,
				"orgIds");
		List<Object> orgIds = orgs==null?null:orgs.toList();
		selAll(params.getInt("staffId"), orgIds);
		JSONObject ret = TapestryAssist.buildSelGroupInit(allPosition, selPosition,
				new String[] { "caOrganization.orgName,orgName1" }, null);
		return retStream(ret.toString(true));
	}

	void onActivate(int staffId) {
		this.staffId = staffId;
		orgTree = orgService.createOrgTree(I18NConvert);
		selAll(staffId, null);
	}

	private void selAll(int staffId, List<Object> orgIds) {
		List<Integer> orgidsTrue = null;
		if (orgIds != null) {
			orgidsTrue = new ArrayList<Integer>();
			for (Object ele : orgIds) {
				orgidsTrue.add(Integer.parseInt(String.valueOf(ele)));
			}
		}

		Criteria criteria = session.createCriteria(CaPosition.class);
		if (orgidsTrue != null) {
			criteria.add(Restrictions.in("caOrganization.id", orgidsTrue));
		}
		allPosition = criteria.list();
		findGroupId(staffId, orgidsTrue);
	}

	private void findGroupId(int staffId, List<Integer> orgidsTrue) {
		// 查询已选择的群组
		// String alias = "group_"; //查询时的table别名
		Criteria criteriasel = session.createCriteria(CaStaffPosition.class);
		ProjectionList pList = Projections.projectionList();
		pList.add(Projections.property("caPosition.id").as("positionId"));
		criteriasel.setProjection(pList);
		criteriasel.add(Restrictions.eq("caStaff.id", staffId));
		if (orgidsTrue != null) {
			criteriasel.createAlias("caPosition", "g");
			criteriasel.add(Restrictions.in("g.caOrganization.id", orgidsTrue));
		}
		selPosition = criteriasel.list();
	}

	/***
	 * 保存选择的结果
	 * 
	 * @param selIds
	 * @return
	 */
	@CommitAfter
	@OnEvent(value = "save")
	private OperateResult sava(JSONArray selIds) {
		if (selIds == null) {
			return new OperateResult(0, "需要传入要保存的对象");
		}

		// 找到已有的群组
		if (orgs == null || orgs.length() == 0) {
			findGroupId(staffId, null);
		} else {
			List<Integer> orgidsTrue = new ArrayList<Integer>();
			for (int i = 0; i < orgs.length(); i++) {
				orgidsTrue.add(Integer.parseInt(orgs.getString(i)));
			}
			findGroupId(staffId, orgidsTrue);
		}

		int[] oriIds = new int[selPosition.size()];
		for (int i = 0; i < oriIds.length; i++) {
			oriIds[i] = Integer.parseInt(String.valueOf(selPosition.get(i)));
		}
		int[] saveIds = new int[selIds.length()];
		for (int i = 0; i < selIds.length(); i++) {
			saveIds[i] = Integer.parseInt(selIds.getString(i));
		}
		List<Integer> addList = new ArrayList<Integer>();// 新增
		for (int i = 0; i < saveIds.length; i++) {
			if (!ArrayUtils.contains(oriIds, saveIds[i])) {
				addList.add(saveIds[i]);
			}
		}
		if (CollectionUtils.isNotEmpty(addList)) {
			for (Integer positionId : addList) {
				CaStaffPosition saveobj = new CaStaffPosition();
				saveobj.setCaPosition(new CaPosition(positionId));
				saveobj.setCaStaff(new CaStaff(staffId));
				session.save(saveobj);
			}

		}
		List<Integer> delList = new ArrayList<Integer>();// 删除
		for (int i = 0; i < oriIds.length; i++) {
			if (!ArrayUtils.contains(saveIds, oriIds[i])) {
				delList.add(oriIds[i]);
			}
		}

		if (CollectionUtils.isNotEmpty(delList)) {
			hbService
					.getQuery(
							"delete CaStaffPosition where caStaff.id=? and caPosition.id in (:ids)")
					.setParameter(0, staffId)
					.setParameterList("ids", delList).executeUpdate();

		}
		return new OperateResult(1, "保存成功");
	}
}
